package com.juli.school.service.impl;

import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.google.common.collect.Lists;
import com.juli.school.dao.entity.Lottery;
import com.juli.school.dao.entity.LotteryRecord;
import com.juli.school.dao.entity.Point;
import com.juli.school.dao.mapper.LotteryMapper;
import com.juli.school.dao.mapper.LotteryRecordMapper;
import com.juli.school.service.bo.LotteryBo;
import com.juli.school.service.utils.BeanUtils;
import com.juli.school.service.utils.BigWheelDrawUtil;
import com.juli.school.utils.core.model.CommonResp;
import com.juli.school.utils.core.model.PageResp;
import com.juli.school.utils.dao.base.Page;

/**
 * @Description: 抽奖服务
 * @author: wjp
 * @date: 2018年3月24日下午5:14:45
 */
@Service
public class LotteryService {
	private final static Logger logger = LoggerFactory.getLogger(LotteryService.class);

	@Resource
	LotteryMapper lotteryMapper;
	@Resource
	PointService pointService;
	@Resource
	LotteryRecordMapper lotteryRecordMapper;

	/**
	 * @Description: 获取所有奖品列表
	 * @author: wjp
	 * @date: 2018年3月25日下午3:50:25
	 */
	public CommonResp<PageResp<LotteryBo>> listPage(Integer pageSize, Integer pageNo) {
		CommonResp<PageResp<LotteryBo>> commonResp = new CommonResp<PageResp<LotteryBo>>();
		try {
			// 设置分页信息
			Page page = new Page();
			page.setShowCount(pageSize == null ? 8 : pageSize);// 查询几条
			page.setCurrentPage(pageNo == null ? 0 : pageNo);
			LotteryBo req = new LotteryBo();
			req.setPage(page);
			List<Lottery> listPage = lotteryMapper.listPage(req);
			List<LotteryBo> data = Lists.newArrayList();
			for (Lottery lottery : listPage) {
				LotteryBo lotteryBoBo = new LotteryBo();
				BeanUtils.copyProperties(lotteryBoBo, lottery);
				data.add(lotteryBoBo);
			}
			PageResp<LotteryBo> pageResp = new PageResp<>();
			pageResp.setList(data);
			commonResp.success();
			commonResp.setData(pageResp);
		} catch (Exception e) {
			logger.error("获取奖项信息异常", e);
			commonResp.exception("获取奖项列表异常");
		}
		return commonResp;
	}

	/**
	 * @Description: 获取奖品List
	 * @author: wjp
	 * @date: 2018年3月25日下午3:50:47
	 */
	public List<Lottery> queryList(Integer pageSize, Integer pageNo) {
		try {
			// 设置分页信息
			Page page = new Page();
			page.setShowCount(pageSize == null ? 8 : pageSize);// 查询几条
			page.setCurrentPage(pageNo == null ? 0 : pageNo);
			LotteryBo req = new LotteryBo();
			req.setPage(page);
			List<Lottery> listPage = lotteryMapper.listPage(req);
			return listPage;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("获取奖项信息异常", e);
		}
		return null;
	}

	/**
	 * @Description: 新增一条奖品
	 * @author: wjp
	 * @date: 2018年3月25日下午3:51:01
	 */
	public CommonResp<String> add(LotteryBo lotteryBo) {
		CommonResp<String> commonResp = new CommonResp<String>();
		try {
			if (lotteryBo.getNum() == null) {
				lotteryBo.setNum(0);
			}
			if (lotteryBo.getSurplusNum() == null) {
				lotteryBo.setSurplusNum(lotteryBo.getNum());
			}
			lotteryBo.setGmtCreate(new Date());
			lotteryBo.setGmtUpdate(new Date());
			lotteryMapper.insert(lotteryBo);
			commonResp.success();
		} catch (Exception e) {
			logger.error("新增奖品信息异常", e);
			commonResp.exception("新增奖品信息异常" + e.getMessage());
		}
		return commonResp;
	}

	/**
	 * @Description: 抽奖
	 * @author: wjp
	 * @date: 2018年3月25日上午11:59:57
	 */
	public CommonResp<LotteryBo> lotteryDraw(String stuId, Integer pageNo, Integer pageSize, Integer integralNum) {
		CommonResp<LotteryBo> commonResp = new CommonResp<LotteryBo>();
		try {
			if (integralNum == null) {
				commonResp.fail("入参本次扣除积分数量不能为空，扣除积分数量需要小于0");
				return commonResp;
			}
			Point point = new Point(); // 积分变动实体
			point.setStuId(stuId);
			point.setmKind(3);
			point.setReason("抽奖消耗");
			point.setScore(integralNum);
			CommonResp<String> change = pointService.add(point);
			if (change.isSuccess()) { // 成功
				List<Lottery> queryList = this.queryList(pageNo, pageSize);
				for (Lottery lottery : queryList) {
					if (lottery.getSurplusNum() == 0) {// 挑出所有奖品，去除奖品剩余中奖数量为零的奖品
						queryList.remove(lottery);
					}
				}
				Lottery generateAward = BigWheelDrawUtil.generateAward(queryList);// 开始抽奖
				LotteryBo lotteryBo = new LotteryBo();
				if (generateAward == null) {
					generateAward = new Lottery("没有中奖哦~", "0", 0);
				} else {
					synchronized (this) {// 同步代码块保证每次扣除不会出现误差
						Integer surplusNum = generateAward.getSurplusNum();
						if (surplusNum > 0) {// 剩余个数大于0
							generateAward.setSurplusNum(surplusNum - 1);
							lotteryMapper.update(generateAward);
						} else if (surplusNum != -1) {// 小于 0 没有中奖
							generateAward = new Lottery("没有中奖哦~", "0", 0);
						}
					}
				}
				BeanUtils.copyProperties(lotteryBo, generateAward);
				if (generateAward.getIsIntegral() != null && generateAward.getIsIntegral()) {// 抽奖获得增加积分奖励
					point = new Point();// 积分变动实体
					point.setStuId(stuId);
					point.setmKind(3);
					point.setReason("抽奖:" + generateAward.getPrizename());
					point.setScore(Integer.valueOf(generateAward.getPrizeprice()));
					pointService.add(point);
				}
				// 保存中奖记录
				LotteryRecord record = new LotteryRecord();
				record.setStuId(stuId);
				record.setPrizename(generateAward.getPrizename());
				record.setPrizeprice(generateAward.getPrizeprice());
				record.setType(generateAward.getType());
				record.setGmtCreate(new Date());
				record.setGmtUpdate(new Date());
				String snStamp = UUID.randomUUID().toString();
				record.setSnStamp(snStamp);
				lotteryRecordMapper.insert(record);
				commonResp.setData(lotteryBo);
				commonResp.success();
			} else {// 抽奖失败
				commonResp.fail(change.getMsg());
				return commonResp;
			}
		} catch (Exception e) {
			logger.error("获取中奖详情发生异常", e);
			commonResp.exception("获取中奖详情发生异常" + e.getMessage());
		}
		return commonResp;
	}
}
